#!/usr/bin/python2.5
# -*- coding: cp1250 -*-
#
# Copyright 2008 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
kindly.cz application

main page and download page handlers
"""

__author__ = 'Nikola Tepper'

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.api import taskqueue

import string
import settings
import timezones 

from models import *
from datetime import *        
        
class Update(webapp.RequestHandler):
    
    def updateSubcriptions(self,subscriptions):
        
        logging.debug("Updating %i subscriptions" % len(subscriptions))
        
        for subscription in subscriptions: 
            """
            subscription.schedule_weekday ='7'
            subscription.schedule_weekend ='7'
            for i in range(7):
                propName = 'schedule_%s' % str(i)
                setattr(subscription, propName, None)
            continue
            """      
            
            # temp code to convert old styled subcriptions (weekday, weekend) to daily subscriptions
            if subscription.schedule_weekday is not None:
                for i in range(5):
                    propName = 'schedule_%s' % str(i)
                    setattr(subscription, propName, subscription.schedule_weekday)
                subscription.schedule_weekday = None #remove old settings
                
            if subscription.schedule_weekend is not None:
                for i in range(2):
                    propName = 'schedule_%s' % str(i + 5)
                    setattr(subscription, propName, subscription.schedule_weekend)
                subscription.schedule_weekend = None #remove old settings 
            
        logging.debug("Saving %i subscriptions" % len(subscriptions))     
        db.put(subscriptions)
        
        self.response.out.write("updated %i subscriptions<br>" % len(subscriptions))    
   
    def get(self):   
        
        self.response.clear()
        logging.debug("Starting update mode...")
        
        FETCHLIMIT = 100   
             
        query = Subscription.all()            
        query.filter("schedule_weekday != ", None) # old style      
        subscriptions = query.fetch(FETCHLIMIT)
        self.updateSubcriptions(subscriptions)      
        
        query = Subscription.all()            
        query.filter("schedule_weekend != ", None) # old style         
        subscriptions = query.fetch(FETCHLIMIT)
        self.updateSubcriptions(subscriptions)            
        
        self.response.set_status(200)
        self.response.out.write("done")     
        
class Index(webapp.RequestHandler):    
    def get(self):
        self.response.clear()
        self.response.set_status(200)
        self.response.out.write("kindly.cz se updatuje...")
class IndexAll(webapp.RequestHandler):    
    def get(self, url_name):
        self.response.clear()
        self.response.set_status(200)
        self.response.out.write("kindly.cz se updatuje...")
    
def main():
    url_map = [('/updatesitekindly', Update),
               ('/*', Index),
               ('/([-\.\w]+)', IndexAll),]
    
    application = webapp.WSGIApplication(url_map, debug=True)
    run_wsgi_app(application)

if __name__ == '__main__':
    main()